package com.example.micromallsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.micromallsearch.bean.Product;
import com.example.micromallsearch.bean.ProductES;
import com.example.micromallsearch.bean.ProductExample;
import com.example.micromallsearch.mapper.ProductMapper;
import com.example.micromallsearch.service.ElasticsearchTests;
import com.example.micromallsearch.service.ProductService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.List;


@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ElasticsearchTests elasticsearch;


    /**
     * 项目启动时执行一次，将同步mysql商品表的数据发送到kafka，搜索服务监听并存到ES库
     *
     */
    @KafkaListener(topics = "product")
    public void productAll(String message) throws IOException {
        System.out.println("消费product："+message);
        //获取到kafka中的所有product
        List<String> productList= JSON.parseObject(message,new TypeReference<List<String>>(){});

        for (String productStr:productList){
            Product product = JSON.parseObject(productStr, Product.class);
            ProductES productES=new ProductES();
            BeanUtils.copyProperties(product,productES);
            //存入ES,使用对象作为数据  入参为索引、对象
            elasticsearch.addDoc2("product",productES);
        }
    }

    /**
     * 监听商品信息的修改
     *
     */
    @KafkaListener(topics = "productUpdate")
    public void productUpdate(String message) throws IOException {
        System.out.println("消费productUpdate："+message);

        Product product = JSON.parseObject(message, Product.class);
        ProductES productES=new ProductES();
        BeanUtils.copyProperties(product,productES);
        //存入ES,使用对象作为数据  入参为索引、对象
        elasticsearch.addDoc2("product",productES);
        }


}
